import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useWeatherStore } from './weather'
import { useRemindersStore } from './reminders'
import { useNotesStore } from './notes'
import { useICloudStore } from './icloud'
import { useCalendarStore } from './calendar'
import { loadAppsSync } from '@/lib/appLoader'
import type { AppConfig } from '@/types/app'

export interface App {
  id: string
  name: string
  icon: string
  component?: string
  isOpen: boolean
  isMinimized: boolean
  isFocused: boolean
  zIndex: number
  pinnedToDock: boolean  // 是否固定在Dock
}

export interface WindowState {
  id: string
  appId: string
  title: string
  x: number
  y: number
  width: number
  height: number
  isMaximized: boolean
  isMinimized: boolean
  isFocused: boolean
  zIndex: number
}
export interface NotificationBanner {
  id: number
  title: string
  body?: string
  icon?: string
  timeoutMs?: number
  timestamp: number
}

// 设置数据结构（通用 + 墙纸）
export interface SettingsState {
  wallpaper: string
  appearance: 'light' | 'dark' | 'auto'
  accentColor: string
  sidebarIconSize: 'small' | 'medium' | 'large'
  autoHideMenuBar: boolean
  autoHideDock: boolean
  showScrollBars: 'always' | 'whenScrolling' | 'never'
  reduceMotion: boolean
  reduceTransparency: boolean
  focusMode: boolean
}

export const useDesktopStore = defineStore('desktop', () => {
  // 自动加载所有应用配置
  const loadedApps = loadAppsSync()
  
  // 将 AppConfig 转换为 App 格式
  const apps = ref<App[]>(
    loadedApps.map((appConfig: AppConfig) => ({
      id: appConfig.id,
      name: appConfig.name,
      icon: appConfig.icon,
      component: appConfig.id.charAt(0).toUpperCase() + appConfig.id.slice(1), // 将 id 转换为组件名
      isOpen: false,
      isMinimized: false,
      isFocused: false,
      zIndex: 0,
      pinnedToDock: appConfig.pinnedToDock ?? false
    }))
  )

  // 最近打开的应用历史（用于临时区显示）
  const recentApps = ref<string[]>([])

  const windows = ref<WindowState[]>([])
  const maxZIndex = ref(100)
  const showLaunchpad = ref(false)
  const showNotificationCenter = ref(false)
  const showControlCenter = ref(false)
  const currentTime = ref(new Date())
  
  // 壁纸状态 - 默认使用渐变壁纸
  const wallpaper = ref('linear-gradient(135deg, #1a0633 0%, #2d1b4e 25%, #4a2c6b 50%, #6b3d88 75%, #8e4aa5 100%)')
  
  // 系统设置
  const appearance = ref<'light' | 'dark' | 'auto'>('light')
  const accentColor = ref('#007aff')
  const sidebarIconSize = ref<'small' | 'medium' | 'large'>('medium')
  const autoHideMenuBar = ref(false)
  const autoHideDock = ref(false)
  const showScrollBars = ref<'always' | 'whenScrolling' | 'never'>('whenScrolling')
  const reduceMotion = ref(false)
  const reduceTransparency = ref(false)
  const focusMode = ref(false)
  // 右侧通知栏 - Banner 列表
  const notificationBanners = ref<NotificationBanner[]>([])

  // 锁屏/登录状态
  const isLocked = ref(true)
  const isLoggedIn = ref(false) // Apple ID 登录状态
  const lockScreenPassword = ref('') // 锁屏密码，为空表示未设置
  const userAccount = ref({
    username: '',
    email: '',
    avatar: '👤',
    password: '', // 账号密码
    location: {
      province: '四川',
      city: '成都',
      county: '成华区'
    }
  })

  // 更新时间
  setInterval(() => {
    currentTime.value = new Date()
  }, 1000)

  // macOS 风格的窗口层叠偏移量
  const CASCADE_OFFSET = 30 // 每个窗口的偏移量

  /**
   * 计算窗口的智能位置，实现 macOS 风格的层叠效果
   */
  function calculateWindowPosition(width: number, height: number): { x: number; y: number } {
    // 菜单栏高度
    const menuBarHeight = 28
    // 安全边距
    const safeMargin = 20

    // 基础居中位置
    let baseX = (window.innerWidth - width) / 2
    let baseY = (window.innerHeight - height) / 2 - 30

    // 如果没有打开的窗口，直接返回居中位置
    if (windows.value.length === 0) {
      return { x: baseX, y: baseY }
    }

    // 获取所有可见窗口（未最小化的）
    const visibleWindows = windows.value.filter(w => !w.isMinimized)
    
    // 如果所有窗口都被最小化了，返回居中位置
    if (visibleWindows.length === 0) {
      return { x: baseX, y: baseY }
    }

    // 尝试找到一个不重叠的位置
    let attempts = 0
    const maxAttempts = 15 // 最多尝试 15 次层叠
    
    while (attempts < maxAttempts) {
      const offsetX = baseX + (attempts * CASCADE_OFFSET)
      const offsetY = baseY + (attempts * CASCADE_OFFSET)
      
      // 检查是否超出屏幕边界
      const isOutOfBounds = 
        offsetX < safeMargin ||
        offsetY < menuBarHeight + safeMargin ||
        offsetX + width > window.innerWidth - safeMargin ||
        offsetY + height > window.innerHeight - safeMargin

      if (isOutOfBounds) {
        // 如果超出边界，重置到基础位置
        return { x: baseX, y: baseY }
      }

      // 检查是否与现有窗口重叠（检查左上角是否重叠）
      const hasOverlap = visibleWindows.some(w => {
        // 只检查左上角位置是否完全相同（允许小范围误差）
        const xOverlap = Math.abs(w.x - offsetX) < 5
        const yOverlap = Math.abs(w.y - offsetY) < 5
        return xOverlap && yOverlap
      })

      if (!hasOverlap) {
        return { x: offsetX, y: offsetY }
      }

      attempts++
    }

    // 如果所有位置都重叠，返回基础位置
    return { x: baseX, y: baseY }
  }

  function openApp(appId: string) {
    const app = apps.value.find(a => a.id === appId)
    if (!app) return

    if (app.isOpen) {
      // 如果已经打开，聚焦窗口
      focusApp(appId)
      return
    }

    app.isOpen = true
    app.isFocused = true
    app.zIndex = ++maxZIndex.value

    // 如果应用未固定到Dock，添加到最近打开列表
    if (!app.pinnedToDock) {
      // 移除已存在的记录
      const index = recentApps.value.indexOf(appId)
      if (index > -1) {
        recentApps.value.splice(index, 1)
      }
      // 添加到开头（不限制数量，由显示逻辑控制）
      recentApps.value.unshift(appId)
      // 保存到localStorage
      saveDockToStorage()
    }

    // 创建窗口
    let windowWidth = Math.min(800, window.innerWidth * 0.8)
    let windowHeight = Math.min(600, window.innerHeight * 0.7)
    
    // 计算器使用固定的小窗口尺寸
    if (appId === 'calculator') {
      windowWidth = 300
      windowHeight = 480
    }
    
    // 使用智能位置计算
    const { x: windowX, y: windowY } = calculateWindowPosition(windowWidth, windowHeight)

    windows.value.push({
      id: `window-${appId}-${Date.now()}`,
      appId,
      title: app.name,
      x: windowX,
      y: windowY,
      width: windowWidth,
      height: windowHeight,
      isMaximized: false,
      isMinimized: false,
      isFocused: true,
      zIndex: app.zIndex
    })

    // 取消其他应用的焦点
    apps.value.forEach(a => {
      if (a.id !== appId) {
        a.isFocused = false
      }
    })
  }

  function closeApp(appId: string) {
    const app = apps.value.find(a => a.id === appId)
    if (app) {
      app.isOpen = false
      app.isMinimized = false
      app.isFocused = false
    }
    windows.value = windows.value.filter(w => w.appId !== appId)
  }

  function minimizeApp(appId: string) {
    const app = apps.value.find(a => a.id === appId)
    if (app) {
      app.isMinimized = true
      app.isFocused = false
    }
    const window = windows.value.find(w => w.appId === appId)
    if (window) {
      window.isMinimized = true
      window.isFocused = false
    }
  }

  function focusApp(appId: string) {
    const app = apps.value.find(a => a.id === appId)
    if (!app) return

    app.isFocused = true
    app.isMinimized = false
    app.zIndex = ++maxZIndex.value

    const window = windows.value.find(w => w.appId === appId)
    if (window) {
      window.isFocused = true
      window.isMinimized = false
      window.zIndex = app.zIndex
    }

    // 如果应用未固定到Dock，更新最近运行列表（移到最前面）
    if (!app.pinnedToDock && app.isOpen) {
      const index = recentApps.value.indexOf(appId)
      if (index > -1) {
        // 如果已经在列表中，移除后添加到开头
        recentApps.value.splice(index, 1)
      }
      recentApps.value.unshift(appId)
      // 保存到localStorage
      saveDockToStorage()
    }

    // 取消其他应用的焦点
    apps.value.forEach(a => {
      if (a.id !== appId) {
        a.isFocused = false
      }
    })
    windows.value.forEach(w => {
      if (w.appId !== appId) {
        w.isFocused = false
      }
    })
  }

  function toggleLaunchpad() {
    showLaunchpad.value = !showLaunchpad.value
    showNotificationCenter.value = false
    showControlCenter.value = false
  }

  function toggleNotificationCenter() {
    showNotificationCenter.value = !showNotificationCenter.value
    showLaunchpad.value = false
    showControlCenter.value = false
  }

  function toggleControlCenter() {
    showControlCenter.value = !showControlCenter.value
    showLaunchpad.value = false
    showNotificationCenter.value = false
  }

  function updateWindowPosition(windowId: string, x: number, y: number) {
    const window = windows.value.find(w => w.id === windowId)
    if (window) {
      window.x = x
      window.y = y
    }
  }

  function updateWindowSize(windowId: string, width: number, height: number) {
    const window = windows.value.find(w => w.id === windowId)
    if (window) {
      window.width = width
      window.height = height
    }
  }

  function toggleMaximize(windowId: string) {
    const window = windows.value.find(w => w.id === windowId)
    if (window) {
      window.isMaximized = !window.isMaximized
    }
  }

  // -------------------- 设置持久化与统一接口 --------------------
  const SETTINGS_STORAGE_KEY = 'vue-desktop:settings'
  const DOCK_STORAGE_KEY = 'vue-desktop:dock'

  // -------------------- Dock 持久化 --------------------
  
  // 保存Dock状态到localStorage
  function saveDockToStorage() {
    try {
      const dockData = {
        pinnedApps: apps.value.map(app => ({
          id: app.id,
          pinnedToDock: app.pinnedToDock
        })),
        recentApps: recentApps.value
      }
      localStorage.setItem(DOCK_STORAGE_KEY, JSON.stringify(dockData))
    } catch (_) {
      // 忽略存储错误
    }
  }

  // 从localStorage加载Dock状态
  function loadDockFromStorage() {
    try {
      const raw = localStorage.getItem(DOCK_STORAGE_KEY)
      if (!raw) return
      
      const parsed = JSON.parse(raw)
      
      // 恢复pinnedToDock状态
      if (parsed.pinnedApps && Array.isArray(parsed.pinnedApps)) {
        parsed.pinnedApps.forEach((savedApp: { id: string; pinnedToDock: boolean }) => {
          const app = apps.value.find(a => a.id === savedApp.id)
          if (app) {
            app.pinnedToDock = savedApp.pinnedToDock
          }
        })
      }
      
      // 恢复recentApps历史
      if (parsed.recentApps && Array.isArray(parsed.recentApps)) {
        recentApps.value = parsed.recentApps
      }
    } catch (_) {
      // 忽略解析错误
    }
  }

  // 清除Dock缓存
  function clearDockCache() {
    try {
      // 重置所有应用的固定状态为默认值
      apps.value.forEach(app => {
        const defaultPinned = ['finder', 'safari', 'appstore', 'settings'].includes(app.id)
        app.pinnedToDock = defaultPinned
      })
      
      // 清空最近应用列表
      recentApps.value = []
      
      // 移除本地存储
      localStorage.removeItem(DOCK_STORAGE_KEY)
    } catch (_) {
      // 忽略错误
    }
  }

  function getSettings(): SettingsState {
    return {
      wallpaper: wallpaper.value,
      appearance: appearance.value,
      accentColor: accentColor.value,
      sidebarIconSize: sidebarIconSize.value,
      autoHideMenuBar: autoHideMenuBar.value,
      autoHideDock: autoHideDock.value,
      showScrollBars: showScrollBars.value,
      reduceMotion: reduceMotion.value,
      reduceTransparency: reduceTransparency.value,
      focusMode: focusMode.value,
    }
  }

  function applySettingsSideEffects(updated: Partial<SettingsState>) {
    if (updated.appearance !== undefined) applyAppearance()
    if (updated.accentColor !== undefined) applyAccentColor()
    if (updated.showScrollBars !== undefined) applyScrollBarStyle()
    if (updated.reduceMotion !== undefined) applyMotionPreference()
  }

  function saveSettingsToStorage() {
    try {
      const snapshot = getSettings()
      localStorage.setItem(SETTINGS_STORAGE_KEY, JSON.stringify(snapshot))
    } catch (_) {
      // 忽略存储错误（如隐私模式）
    }
  }

  function loadSettingsFromStorage() {
    try {
      const raw = localStorage.getItem(SETTINGS_STORAGE_KEY)
      if (!raw) return
      const parsed = JSON.parse(raw) as Partial<SettingsState>
      // 仅更新数据，不保存（避免循环），不应用副作用（初始化时统一应用）
      if (parsed.wallpaper !== undefined) wallpaper.value = parsed.wallpaper
      if (parsed.appearance !== undefined) appearance.value = parsed.appearance
      if (parsed.accentColor !== undefined) accentColor.value = parsed.accentColor
      if (parsed.sidebarIconSize !== undefined) sidebarIconSize.value = parsed.sidebarIconSize
      if (parsed.autoHideMenuBar !== undefined) autoHideMenuBar.value = parsed.autoHideMenuBar
      if (parsed.autoHideDock !== undefined) autoHideDock.value = parsed.autoHideDock
      if (parsed.showScrollBars !== undefined) showScrollBars.value = parsed.showScrollBars
      if (parsed.reduceMotion !== undefined) reduceMotion.value = parsed.reduceMotion
      if (parsed.reduceTransparency !== undefined) reduceTransparency.value = parsed.reduceTransparency
      if (parsed.focusMode !== undefined) focusMode.value = parsed.focusMode
    } catch (_) {
      // 忽略解析错误
    }
  }

  function updateSettings(partial: Partial<SettingsState>) {
    const changed: Partial<SettingsState> = {}

    if (partial.wallpaper !== undefined) {
      wallpaper.value = partial.wallpaper
      changed.wallpaper = partial.wallpaper
    }
    if (partial.appearance !== undefined) {
      appearance.value = partial.appearance
      changed.appearance = partial.appearance
    }
    if (partial.accentColor !== undefined) {
      accentColor.value = partial.accentColor
      changed.accentColor = partial.accentColor
    }
    if (partial.sidebarIconSize !== undefined) {
      sidebarIconSize.value = partial.sidebarIconSize
      changed.sidebarIconSize = partial.sidebarIconSize
    }
    if (partial.autoHideMenuBar !== undefined) {
      autoHideMenuBar.value = partial.autoHideMenuBar
      changed.autoHideMenuBar = partial.autoHideMenuBar
    }
    if (partial.autoHideDock !== undefined) {
      autoHideDock.value = partial.autoHideDock
      changed.autoHideDock = partial.autoHideDock
    }
    if (partial.showScrollBars !== undefined) {
      showScrollBars.value = partial.showScrollBars
      changed.showScrollBars = partial.showScrollBars
    }
    if (partial.reduceMotion !== undefined) {
      reduceMotion.value = partial.reduceMotion
      changed.reduceMotion = partial.reduceMotion
    }
    if (partial.reduceTransparency !== undefined) {
      reduceTransparency.value = partial.reduceTransparency
      changed.reduceTransparency = partial.reduceTransparency
    }
    if (partial.focusMode !== undefined) {
      focusMode.value = partial.focusMode
      changed.focusMode = partial.focusMode
    }

    applySettingsSideEffects(changed)
    saveSettingsToStorage()
  }

  // 预留后端接口 - 未来可替换为实际 API 调用
  async function fetchSettingsFromServer(): Promise<SettingsState | null> {
    // TODO: 从后端获取设置
    // 示例：const response = await fetch('/api/settings')
    // const data = await response.json()
    // return data as SettingsState
    return null
  }

  async function pushSettingsToServer(state?: Partial<SettingsState>): Promise<boolean> {
    // TODO: 将设置同步到后端
    // 示例：const response = await fetch('/api/settings', {
    //   method: 'POST',
    //   headers: { 'Content-Type': 'application/json' },
    //   body: JSON.stringify(state || getSettings())
    // })
    // return response.ok
    void state
    return false
  }

  async function syncSettingsWithServer(): Promise<void> {
    // 完整的同步流程：先从服务器获取，合并本地设置，再推送
    try {
      const serverSettings = await fetchSettingsFromServer()
      if (serverSettings) {
        updateSettings(serverSettings)
      } else {
        // 服务器无设置，推送本地设置
        await pushSettingsToServer()
      }
    } catch (error) {
      console.error('设置同步失败:', error)
    }
  }

  function setWallpaper(value: string) {
    wallpaper.value = value
    saveSettingsToStorage()
  }
  
  function setAppearance(value: 'light' | 'dark' | 'auto') {
    appearance.value = value
    applyAppearance()
    saveSettingsToStorage()
  }
  
  function setAccentColor(color: string) {
    accentColor.value = color
    applyAccentColor()
    saveSettingsToStorage()
  }
  
  function setSidebarIconSize(size: 'small' | 'medium' | 'large') {
    sidebarIconSize.value = size
    saveSettingsToStorage()
  }
  
  function setAutoHideMenuBar(value: boolean) {
    autoHideMenuBar.value = value
    saveSettingsToStorage()
  }
  
  function setAutoHideDock(value: boolean) {
    autoHideDock.value = value
    saveSettingsToStorage()
  }
  
  function setShowScrollBars(value: 'always' | 'whenScrolling' | 'never') {
    showScrollBars.value = value
    applyScrollBarStyle()
    saveSettingsToStorage()
  }
  
  function setReduceMotion(value: boolean) {
    reduceMotion.value = value
    applyMotionPreference()
    saveSettingsToStorage()
  }
  
  function setReduceTransparency(value: boolean) {
    reduceTransparency.value = value
    saveSettingsToStorage()
  }

  function setFocusMode(value: boolean) {
    focusMode.value = value
    saveSettingsToStorage()
  }
  
  // 应用外观设置
  function applyAppearance() {
    const html = document.documentElement
    if (appearance.value === 'dark') {
      html.classList.add('dark-mode')
    } else if (appearance.value === 'light') {
      html.classList.remove('dark-mode')
    } else {
      // auto - 根据系统偏好
      const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches
      if (isDark) {
        html.classList.add('dark-mode')
      } else {
        html.classList.remove('dark-mode')
      }
    }
  }
  
  // 应用强调色
  function applyAccentColor() {
    document.documentElement.style.setProperty('--accent-color', accentColor.value)
    const rgb = hexToRgb(accentColor.value)
    if (rgb) {
      document.documentElement.style.setProperty('--accent-rgb', `${rgb.r}, ${rgb.g}, ${rgb.b}`)
    }
  }

  function hexToRgb(hex: string): { r: number; g: number; b: number } | null {
    let cleaned = hex.trim().toLowerCase()
    if (cleaned.startsWith('#')) cleaned = cleaned.slice(1)
    if (cleaned.length === 3) {
      cleaned = cleaned.split('').map(c => c + c).join('')
    }
    if (cleaned.length !== 6) return null
    const num = Number.parseInt(cleaned, 16)
    // NaN check
    if (Number.isNaN(num)) return null
    return {
      r: (num >> 16) & 255,
      g: (num >> 8) & 255,
      b: num & 255,
    }
  }
  
  // 应用滚动条样式
  function applyScrollBarStyle() {
    const html = document.documentElement
    html.setAttribute('data-scrollbar', showScrollBars.value)
  }
  
  // 应用动画偏好
  function applyMotionPreference() {
    const html = document.documentElement
    if (reduceMotion.value) {
      html.classList.add('reduce-motion')
    } else {
      html.classList.remove('reduce-motion')
    }
  }
  
  // 初始化：加载设置、用户信息和Dock状态
  loadSettingsFromStorage()
  loadUserFromStorage()
  loadDockFromStorage()
  applyAppearance()
  applyAccentColor()
  applyScrollBarStyle()
  applyMotionPreference()

  // 通知栏：推送一条通知
  function notify(payload: { title: string; body?: string; icon?: string; timeoutMs?: number }) {
    const id = Date.now() + Math.floor(Math.random() * 1000)
    const banner: NotificationBanner = {
      id,
      title: payload.title,
      body: payload.body,
      icon: payload.icon,
      timeoutMs: payload.timeoutMs ?? 4000,
      timestamp: Date.now(),
    }
    notificationBanners.value.unshift(banner)
    if (banner.timeoutMs && banner.timeoutMs > 0) {
      setTimeout(() => removeNotification(id), banner.timeoutMs)
    }
  }

  function removeNotification(id: number) {
    notificationBanners.value = notificationBanners.value.filter(b => b.id !== id)
  }

  function clearNotifications() {
    notificationBanners.value = []
  }

  // Apple ID 登录
  function loginWithAppleID(email: string, password: string): boolean {
    if (email && password) {
      isLoggedIn.value = true
      userAccount.value = {
        username: email.split('@')[0],
        email: email,
        avatar: '👤',
        password: password,
        location: userAccount.value.location || {
          province: '四川',
          city: '成都',
          county: '成华区'
        }
      }
      isLocked.value = false
      saveUserToStorage()
      return true
    }
    return false
  }

  // 锁屏解锁（仅使用锁屏密码）
  function unlockScreen(password: string): boolean {
    // 只能使用锁屏密码解锁
    if (lockScreenPassword.value && password === lockScreenPassword.value) {
      isLocked.value = false
      return true
    }
    return false
  }

  // 锁定屏幕
  function lockScreen() {
    // 只有已登录用户才能锁定屏幕
    if (isLoggedIn.value) {
      isLocked.value = true
    }
  }

  // 设置锁屏密码
  function setLockScreenPassword(password: string) {
    lockScreenPassword.value = password
    saveUserToStorage()
  }

  // 更新用户地区信息
  function updateUserLocation(province: string, city: string, county: string) {
    if (isLoggedIn.value) {
      userAccount.value.location = {
        province,
        city,
        county
      }
      saveUserToStorage()
      
      // 通知天气APP更新
      const weatherStore = useWeatherStore()
      weatherStore.setLocation({ province, city, county })
      
      return true
    }
    return false
  }

  // 退出登录
  function logout() {
    isLoggedIn.value = false
    isLocked.value = true
    lockScreenPassword.value = ''
    userAccount.value = {
      username: '',
      email: '',
      avatar: '👤',
      password: '',
      location: {
        province: '四川',
        city: '成都',
        county: '成华区'
      }
    }
    saveUserToStorage()
  }

  // 保存用户信息到本地存储（仅保存必要信息，不保存密码）
  function saveUserToStorage() {
    try {
      const userData = {
        isLoggedIn: isLoggedIn.value,
        lockScreenPassword: lockScreenPassword.value, // 只保存锁屏密码
        userAccount: {
          username: userAccount.value.username,
          email: userAccount.value.email,
          avatar: userAccount.value.avatar,
          location: userAccount.value.location
          // 不保存 password
        }
      }
      localStorage.setItem('vue-desktop:user', JSON.stringify(userData))
    } catch (_) {
      // 忽略存储错误
    }
  }

  // 从本地存储加载用户信息
  function loadUserFromStorage() {
    try {
      const raw = localStorage.getItem('vue-desktop:user')
      if (!raw) return
      const parsed = JSON.parse(raw)
      if (parsed.isLoggedIn) {
        isLoggedIn.value = parsed.isLoggedIn
        lockScreenPassword.value = parsed.lockScreenPassword || ''
        userAccount.value = {
          ...parsed.userAccount,
          password: '', // 密码不从缓存加载
          location: parsed.userAccount.location || {
            province: '四川',
            city: '成都',
            county: '成华区'
          }
        }
      }
    } catch (_) {
      // 忽略解析错误
    }
  }

  // 清除所有缓存并重置登录状态（重新登录用）
  function clearAllCache() {
    // 关闭所有打开的应用
    apps.value.forEach(app => {
      if (app.isOpen) {
        app.isOpen = false
        app.isMinimized = false
        app.isFocused = false
      }
    })
    
    // 清空所有窗口
    windows.value = []
    
    // 关闭所有面板
    showLaunchpad.value = false
    showNotificationCenter.value = false
    showControlCenter.value = false
    
    // 重置登录状态
    isLoggedIn.value = false
    isLocked.value = true
    lockScreenPassword.value = ''
    userAccount.value = {
      username: '',
      email: '',
      avatar: '👤',
      password: '',
      location: {
        province: '四川',
        city: '成都',
        county: '成华区'
      }
    }
    
    // 清除天气缓存
    const weatherStore = useWeatherStore()
    weatherStore.clearWeatherCache()
    
    // 清除提醒事项缓存
    const remindersStore = useRemindersStore()
    remindersStore.clearRemindersCache()
    
    // 清除备忘录缓存
    const notesStore = useNotesStore()
    notesStore.clearNotesCache()
    
    // 清除iCloud缓存
    const icloudStore = useICloudStore()
    icloudStore.clearICloudCache()
    
    // 清除日历缓存
    const calendarStore = useCalendarStore()
    calendarStore.clearCalendarCache()
    
    // 清除Dock缓存
    clearDockCache()
    
    // 清除本地存储
    try {
      localStorage.removeItem('vue-desktop:user')
    } catch (_) {
      // 忽略错误
    }
  }

  // 注销系统（清除所有数据，包括设置）
  function logoutSystem() {
    // 关闭所有打开的应用
    apps.value.forEach(app => {
      if (app.isOpen) {
        app.isOpen = false
        app.isMinimized = false
        app.isFocused = false
      }
    })
    
    // 清空所有窗口
    windows.value = []
    
    // 关闭所有面板
    showLaunchpad.value = false
    showNotificationCenter.value = false
    showControlCenter.value = false
    
    // 重置登录状态
    isLoggedIn.value = false
    isLocked.value = true
    lockScreenPassword.value = ''
    userAccount.value = {
      username: '',
      email: '',
      avatar: '👤',
      password: '',
      location: {
        province: '四川',
        city: '成都',
        county: '成华区'
      }
    }
    
    // 重置所有设置为默认值
    wallpaper.value = 'linear-gradient(135deg, #1a0633 0%, #2d1b4e 25%, #4a2c6b 50%, #6b3d88 75%, #8e4aa5 100%)'
    appearance.value = 'light'
    accentColor.value = '#007aff'
    sidebarIconSize.value = 'medium'
    autoHideMenuBar.value = false
    autoHideDock.value = false
    showScrollBars.value = 'whenScrolling'
    reduceMotion.value = false
    reduceTransparency.value = false
    focusMode.value = false
    
    // 清除天气缓存
    const weatherStore = useWeatherStore()
    weatherStore.clearWeatherCache()
    
    // 清除提醒事项缓存
    const remindersStore = useRemindersStore()
    remindersStore.clearRemindersCache()
    
    // 清除备忘录缓存
    const notesStore = useNotesStore()
    notesStore.clearNotesCache()
    
    // 清除所有本地存储
    try {
      localStorage.removeItem('vue-desktop:user')
      localStorage.removeItem('vue-desktop:settings')
    } catch (_) {
      // 忽略错误
    }
    
    // 重新应用默认设置
    applyAppearance()
    applyAccentColor()
    applyScrollBarStyle()
    applyMotionPreference()
  }

  // 切换应用固定状态
  function togglePinApp(appId: string) {
    const app = apps.value.find(a => a.id === appId)
    if (!app) return

    app.pinnedToDock = !app.pinnedToDock

    // 如果取消固定，添加到最近列表
    if (!app.pinnedToDock) {
      const index = recentApps.value.indexOf(appId)
      if (index === -1) {
        // 如果不在最近列表中，添加到开头
        recentApps.value.unshift(appId)
      }
    }

    // 如果固定，从最近列表移除
    if (app.pinnedToDock) {
      const index = recentApps.value.indexOf(appId)
      if (index > -1) {
        recentApps.value.splice(index, 1)
      }
    }

    // 保存到localStorage
    saveDockToStorage()
  }

  return {
    apps,
    recentApps,
    windows,
    showLaunchpad,
    showNotificationCenter,
    showControlCenter,
    currentTime,
    wallpaper,
    appearance,
    accentColor,
    sidebarIconSize,
    autoHideMenuBar,
    autoHideDock,
    showScrollBars,
    reduceMotion,
    reduceTransparency,
    focusMode,
    notificationBanners,
    isLocked,
    isLoggedIn,
    lockScreenPassword,
    userAccount,
    loginWithAppleID,
    unlockScreen,
    lockScreen,
    setLockScreenPassword,
    updateUserLocation,
    logout,
    clearAllCache,
    logoutSystem,
    openApp,
    closeApp,
    minimizeApp,
    focusApp,
    togglePinApp,
    toggleLaunchpad,
    toggleNotificationCenter,
    toggleControlCenter,
    updateWindowPosition,
    updateWindowSize,
    toggleMaximize,
    setWallpaper,
    setAppearance,
    setAccentColor,
    setSidebarIconSize,
    setAutoHideMenuBar,
    setAutoHideDock,
    setShowScrollBars,
    setReduceMotion,
    setReduceTransparency,
    setFocusMode,
    // 设置持久化 & API
    getSettings,
    updateSettings,
    saveSettingsToStorage,
    loadSettingsFromStorage,
    fetchSettingsFromServer,
    pushSettingsToServer,
    syncSettingsWithServer,
    notify,
    removeNotification,
    clearNotifications
  }
})

